
import cacheUtil from "@/utils/cacheUtil";
import {toRaw} from "vue";

// 需要缓存的key
const keys = ["settings"]
const piniaPlugin = (key) => {
    const piniaKey = 'PiniaKey'
    return (context) => {
        const {store} = context
        if (keys.indexOf(store.$id) < 0 ){
            return
        }
        const data = cacheUtil.local.get(`${key ?? piniaKey}-${store.$id}`)
        // 每次 pinia 中的状态发生改变时，都会执行 $subscribe
        store.$subscribe(() => {
            // store.$state 需要转换成普通对象，可以console.log看看
            cacheUtil.local.set(`${key ?? piniaKey}-${store.$id}`, toRaw(store.$state))
        })
        // 即将 data 解构，后重新赋值给 pinia 的 state，实现持久化
        return {
            ...data
        }
    }
}
const store = createPinia();
store.use(piniaPlugin())

export const initStore = (app) => {
    app.use(store);
}

export {store};
